package com.simple.datax.transform.tcs;

import java.util.HashMap;
import java.util.Map;

import javax.xml.namespace.QName;

import net.easipay.ec.v2.ECFlow201Document;
import net.easipay.ec.v2.ECFlowType;
import net.easipay.ec.v2.ECFlowType.ActionList;
import net.easipay.ec.v2.ECLinkManType;
import net.easipay.ec.v2.ECLinkManType.ECLinkMan;
import net.easipay.ec.v2.ECUserType;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;

import cn.gov.chinaport.tcs.flow.TcsDataType;
import cn.gov.chinaport.tcs.flow.TcsFlow201Document;
import cn.gov.chinaport.tcs.flow.TcsFlow201Document.TcsFlow201;
import cn.gov.chinaport.tcs.flow.TcsFlowType;
import cn.gov.chinaport.tcs.flow.TcsFlowType.ActionList.ActionId;
import cn.gov.chinaport.tcs.flow.TcsLinkManType;
import cn.gov.chinaport.tcs.flow.TcsLinkManType.TcsLinkMan;
import cn.gov.chinaport.tcs.flow.TcsUserType;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.simple.datax.api.TransformerException;
import com.simple.datax.transform.util.TransformUtils;

/**
 * @Title: Ec2TcsFlowTransformer.java
 * @Package com.simple.datax.transform.tcs
 * @Description: 转换从Ec到Tcs的流程头
 * @author Paladin Chen
 * @date 2013-1-8 下午3:26:29
 * @version V1.0
 */
public class Ec2TcsFlowTransformer {
	private static final Logger logger = LoggerFactory.getLogger(Ec2TcsFlowTransformer.class);

	public TcsFlow201Document transform(ECFlow201Document xmlDoc) throws TransformerException {
		TcsFlow201Document tcsflowdoc = TcsFlow201Document.Factory.newInstance();
		TcsFlow201 tcsflow = tcsflowdoc.addNewTcsFlow201();

		//
		ECFlowType ecflowT = xmlDoc.getECFlow201().getECFlow();
		if (ecflowT != null) {
			TcsFlowType flowType = tcsflow.addNewTcsFlow();
			flowType.setBpNo(TransformUtils.changeNullToBlank(ecflowT.getBpNo()));
			flowType.setCorpTaskId(TransformUtils.changeNullToBlank(ecflowT.getCorpTaskId()));

			String taskid = TransformUtils.changeNullToBlank(ecflowT.getTaskId());
			// 如果原始报文中的messageid为null，则使用taskid填充
			if (ecflowT.getMessageId() != null) {
				flowType.setMessageId(ecflowT.getMessageId());
			} else {
				flowType.setMessageId(taskid);
			}

			flowType.setTaskControl(TransformUtils.changeNullToBlank(ecflowT.getTaskControl()));
			flowType.setTaskId(taskid);
			flowType.setTaskNote(TransformUtils.changeNullToBlank(ecflowT.getTaskNote()));

			ActionList ecal = ecflowT.getActionList();
			if (ecal != null) {
				cn.gov.chinaport.tcs.flow.TcsFlowType.ActionList actionList = flowType.addNewActionList();

				for (String acid : ecal.getActionIdArray()) {
					ActionId actionId = actionList.addNewActionId();
					actionId.setStringValue(TransformUtils.changeNullToBlank(acid));
				}
			}
		}

		// 用户类型
		ECUserType ecuser = xmlDoc.getECFlow201().getECUser();
		if (ecuser != null) {
			TcsUserType tcsuser = tcsflow.addNewTcsUser();
			tcsuser.setUserId(TransformUtils.changeNullToBlank(ecuser.getUserId()));

			tcsuser.setUserPrivateKey(TransformUtils.changeNullToBlank(ecuser.getUserPrivateKey()));
		}

		// 联系人
		ECLinkManType ecul = xmlDoc.getECFlow201().getECLink();
		if (ecul != null) {
			ECLinkMan[] ecmen = ecul.getECLinkManArray();

			if (ecmen != null && ecmen.length > 0) {
				TcsLinkManType tcslink = tcsflow.addNewTcsLink();
				for (ECLinkMan eclinkman : ecul.getECLinkManArray()) {
					TcsLinkMan tcslinkman = tcslink.addNewTcsLinkMan();

					tcslinkman.setAddress(TransformUtils.changeNullToBlank(eclinkman.getAddress()));
					tcslinkman.setDepartment(TransformUtils.changeNullToBlank(eclinkman.getDepartment()));
					tcslinkman.setDuty(TransformUtils.changeNullToBlank(eclinkman.getDuty()));
					tcslinkman.setEmail(TransformUtils.changeNullToBlank(eclinkman.getEmail()));
					tcslinkman.setFax(TransformUtils.changeNullToBlank(eclinkman.getFax()));
					tcslinkman.setImCode(TransformUtils.changeNullToBlank(eclinkman.getImCode()));
					tcslinkman.setImType(TransformUtils.changeNullToBlank(eclinkman.getImType()));
					tcslinkman.setMobile(TransformUtils.changeNullToBlank(eclinkman.getMobile()));
					tcslinkman.setName(TransformUtils.changeNullToBlank(eclinkman.getName()));
					tcslinkman.setTelephone(TransformUtils.changeNullToBlank(eclinkman.getTelephone()));
					tcslinkman.setZipCode(TransformUtils.changeNullToBlank(eclinkman.getZipCode()));
				}
			}
		}

		// 报文内容
		if (xmlDoc.getECFlow201().getECData() != null) {
			String srcData = xmlDoc.getECFlow201().getECData().xmlText();
			String srcDataType;

			try {
				XmlObject catdoc2 = XmlObject.Factory.parse(srcData);
				srcDataType = catdoc2.getDomNode().getFirstChild().getNodeName();
				// logger.debug(srcDataType);

				// 目前只对报关单进行转换
				if ("DeclarationDocument".equalsIgnoreCase(srcDataType)) {
					XmlOptions xo = new XmlOptions();
					xo.setUseDefaultNamespace();
					Map<String, String> nms = new HashMap<String, String>();
					nms.put("xsi:schemaLocation", "http://www.chinaport.gov.cn/tcs/v2 Declaration.xsd");
					nms.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
					nms.put("tcs", "http://www.chinaport.gov.cn/tcs/v2");
					nms.put("", null);
					nms.put("v2", null);
					xo.setLoadSubstituteNamespaces(nms);

					// Map<String, String> nms1 = new HashMap<String, String>();
					// nms1.put("", "http://www.easipay.net/ec/v2");
					// nms1.put("v2", "http://www.chinaport.gov.cn/tcs/v2");
					// xo.setLoadAdditionalNamespaces(nms1);
					// xo.setSaveImplicitNamespaces(nms1);

					xo.setSavePrettyPrint();
					xo.setSaveNamespacesFirst();

					srcData = Ec2TcsDecTransformer.transform(srcData);

					TcsDataType tcsDataType = tcsflow.addNewTcsData();
					tcsDataType.set(XmlObject.Factory.parse(srcData, xo));

					// XmlCursor xc = tcsDataType.newCursor();
					// System.out.println("&&&&&&&&&&&&&&&&&1:"+xc.getDomNode().getNodeName());
					// xc.toFirstChild();
					// System.out.println("&&&&&&&&&&&&&&&&&1:"+xc.getDomNode().getNodeName());
					// xc.toNextToken();
					// //xc.insertNamespace("", null);
					// //xc.insertNamespace("v2", "");
					// xc.removeAttribute(new
					// QName("http://www.chinaport.gov.cn/tcs/v2", "v2",
					// "xmlns"));
					// xc.removeAttribute(new
					// QName("http://www.easipay.net/ec/v2", "", "xmlns"));
					// System.out.println("&&&&&&&&&&&&&&&&&1:"+xc.getName());
					//
					// xc.dispose();

				} else {
					TcsDataType tcsDataType = tcsflow.addNewTcsData();
					tcsDataType.set(XmlObject.Factory.parse(srcData));
				}
				// logger.debug("Mapping的TCS报文：" + srcData);
			} catch (Exception e) {
				logger.error("Cannot parse flow data; Now will ignore this error.");

				throw new TransformerException("Parse Flow Data Error.", e);
			}
		}
		return tcsflowdoc;
	}
}
